<template>
	<a-modal v-bind="options" class="invoiceing-detail-dialog" :footer="undefined">
		<a-form ref="formRef" layout="vertical" :model="form" :validate-messages="validateMessages">
			<a-form-item name="email" label="邮箱地址:" :rules="[{type: 'email', required: true}]">
				<a-input v-model:value="form.email" placeholder="请输入邮箱地址" />
				<span class="pour-text" v-color="{color: 'warning'}">注：已冲红的发票无法发送至邮箱！</span>
			</a-form-item>
		</a-form>
		<template #footer>
			<a-button @click="emits('close')">取消</a-button>
			<a-button type="primary" :loading="loading" @click="confirmSending">确认发送</a-button>
		</template>
	</a-modal>
</template>

<script setup lang="ts">
	import {reactive, ref, toRef, watch} from 'vue'
	import {updateEmail} from '@/api/invoicing-history'
	import {message} from 'ant-design-vue'

	const props = defineProps<{
		id?: string
		processInstanceId?: string
		visible?: boolean
		email?: string
	}>()
	const emits = defineEmits(['update:visible', 'close', 'success'])

	const form = reactive({
		email: ''
	})

	const loading = ref(false)
	const options = reactive({
		title: '发送邮箱',
		width: 500,
		centered: true,
		maskClosable: false,
		destroyOnClose: true,
		visible: toRef(props, 'visible'),
		onCancel() {
			emits('close')
		}
	})
	const formRef = ref()

	const validateMessages = {
		types: {
			email: '请输入正确的邮箱地址!'
		}
	}

	watch(
		() => props.visible,
		newVal => {
			form.email = ''
			if (newVal) {
				form.email = props.email as string
			}
		}
	)

	const confirmSending = () => {
		formRef.value.validateFields().then(() => {
			loading.value = true
			updateEmail({
				id: props.id,
				takerEmail: form.email
			}).then(() => {
				loading.value = false

				message.success('发送成功')

				emits('success')
				emits('close')
			})
		})
	}
</script>

<style scoped lang="less">
	.pour-text {
		margin-top: 10px;
		font-size: 12px;
	}
</style>
